package org.example.demos.pattern.chain_pattern_reference;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 校验器配置
 */
@Configuration
public class CheckerConfig {
 
    // 校验器code
    public static final String ORDER_ACCOUNT_CHECKER_CODE = "order_account_checker";
 
    public static final String PAY_ACCOUNT_CHECKER_CODE = "pay_account_checker";
 
    public static final String ORDER_LIMIT_CHECKER_CODE = "order_limit_checker";
 
    // 配置下单校验器链
    public static final List<String> ORDER_CHECKER_PIPELINE = Arrays.stream(new String[]{CheckerConfig.ORDER_ACCOUNT_CHECKER_CODE, CheckerConfig.ORDER_LIMIT_CHECKER_CODE}).collect(Collectors.toList());
 
    // 配置支付校验器链
    public static final List<String> PAY_CHECKER_PIPELINE = Arrays.stream(new String[]{CheckerConfig.PAY_ACCOUNT_CHECKER_CODE}).collect(Collectors.toList());
 
    // 所有的校验器会自动注入这个List
    @Resource
    private List<IChecker> iCheckers;
 
    // 订单校验器自动注入
    @Bean
    public List<IChecker> orderCheckers() {
        return buildCheckFilterBase(CheckerConfig.ORDER_CHECKER_PIPELINE);
    }
 
    // 支付校验器自动注入
    @Bean
    public List<IChecker> payCheckers() {
        return buildCheckFilterBase(CheckerConfig.PAY_CHECKER_PIPELINE);
    }
 
    // 根据配置 取各自检验器code列表下对应的校验器Bean列表
    private List<IChecker> buildCheckFilterBase(List<String> checkerPipeline) {
        List<IChecker> orderChecks = new ArrayList<>();
        if (CollectionUtils.isEmpty(iCheckers)) {
            return orderChecks;
        }
        Map<String, IChecker> map = iCheckers.stream().collect(Collectors.toMap(IChecker::getCheckCode, iChecker -> iChecker));
        checkerPipeline.forEach(code -> {
            if (map.get(code) != null) {
                orderChecks.add(map.get(code));
            }
        });
        return orderChecks;
    }
 
}